﻿using System.Collections.ObjectModel;
using System.Windows;
using Loki.Commands;
using Loki.Engine;

namespace Loki.UI.Wpf
{
    public class BootStrapper<TModel, TMainViewModelType> : BootStrapper, IBootStrapper<TModel, TMainViewModelType>
       where TMainViewModelType : ViewModel<TModel>
    {
        public BootStrapper()
            : base()
        {
            ViewModels = new ObservableCollection<ViewModel<TModel>>();
        }

        /// <summary>
        /// Gets the main view model.
        /// </summary>
        public TMainViewModelType MainViewModel
        {
            get { return MainView.ViewModel as TMainViewModelType; }
        }

        public IView MainView
        {
            get { return MainWindow as IView; }
            protected set
            {
                if (MainView != null)
                {
                    Commands.UnHandle(MainView.ViewModel.Close);
                }
                MainWindow = value as Window;
                if (value != null)
                {
                    Commands.Handle(MainView.ViewModel.Close, MainModel_CanClose, MainModel_Close);
                }
            }
        }

        /// <summary>
        /// Gets the view models.
        /// </summary>
        public ObservableCollection<ViewModel<TModel>> ViewModels
        {
            get;
            private set;
        }

        public override void Start()
        {
            Log.Info("Load main form");
            // Creates main objects
            TMainViewModelType L_MainModel = ContextHelper.GetViewModel<TMainViewModelType>();
            MainView = ContextHelper.GetView<IView>(L_MainModel);

            // activates main form
            MainView.Show();
        }

        #region Model
        public TModel ApplicationModel
        {
            get { return ContextHelper.GetApplicationModel<TModel>(); }
        }
        #endregion

        private void MainModel_CanClose(object sender, CanExecuteCommandEventArgs e)
        {
            e.CanExecute = true;
            Log.Debug("Main ViewModel closing ask");
        }

        private void MainModel_Close(object sender, CommandEventArgs e)
        {
            Log.Debug("Main Viewmodel closing");
        }
    }
}
